<?php

namespace App\Http\Controllers\Repair;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use JWTAuth;
use App\Repository\AdminRepository;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{

    protected $admin;

    public function __construct(AdminRepository $admin)
    {
        $this->admin = $admin;
    }

    public function authenticate(Request $request)
    {

        $this->validate($request, [
            'number' => 'required | integer',
            'password' => 'required'

        ]);

        $credentials = $request->only('number', 'password');

        try{
            if(! $token = JWTAuth::attempt($credentials)){
                return response()->json([ 'error' => 'invalid_credentials',], 401);
            }
        }catch (JWTException $e){
            return response()->json(['error' => 'could_not_create_token'], 500);
        }

        $user = $this->admin->findByNumber($request->input('number'));


        if(!$user->roles()->where(function ($query) {
            $query->where('name', '=', 'repair_officer')
                ->orWhere('name', '=', 'repair_minister');
        })->first()){
            return response()->json([ 'error' => 'invalid_credentials',], 401);
        }

        $token = [
            'token' => $token,
            'user' => $user->user->makeHidden(['weight', 'dormitory_address', 'role',
                'created_at', 'birthday', 'class_id', 'grade', 'area', 'deleted_at', 'major',
                'nickname', 'avatar', 'subscribed_at', 'updated_at', 'id', 'cellphone', 'short_phone']),
        ];

        return response()->json($token);
    }

}
